package com.example.mynote.activity;

import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mynote.R;
import com.example.mynote.base.BaseActivity;
import com.example.mynote.entity.User;

import org.litepal.LitePal;

public class RegisterActivity extends BaseActivity {

    private android.widget.ImageButton titleBack;
    private android.widget.TextView titleText;
    private android.widget.EditText username;
    private android.widget.EditText password;
    private android.widget.EditText conPass;
    private android.widget.Button btnRegister;

    @Override
    protected int initLayout() {
        return R.layout.activity_register;
    }

    @Override
    protected void initView() {

        titleBack = (ImageButton) findViewById(R.id.title_back);
        titleText = (TextView) findViewById(R.id.title_text);
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        conPass = (EditText) findViewById(R.id.con_pass);
        btnRegister = (Button) findViewById(R.id.btn_register);
    }

    @Override
    protected void initData() {

        titleBack.setOnClickListener(v -> onBackPressed());

        titleText.setText("注册");

        btnRegister.setOnClickListener(v -> {
            String name = username.getText().toString();
            String pass = password.getText().toString();
            String con = conPass.getText().toString();
            if (!name.equals("") && !pass.equals("") && !con.equals("")) {
                if (con.equals(pass)) {
                    registerUser(name, con);
                } else {
                    Toast.makeText(this, "两次密码输入不一致", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(RegisterActivity.this, "请检查用户名密码", Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void registerUser(String name, String con) {
        for (User u : LitePal.findAll(User.class)) {
            if (u.getUserName().equals(name)) {
                Toast.makeText(this, "该用户已存在", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        new User(name, con).save();
        Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
        finish();
    }
}